const App = getApp();
const WXAPI = require('../../api/api')
import config from '../../config'
// const baseUrl = require('../../api/config').dev //这里用的是ES6的写法
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isRegister: false,
    error: '',
    formData: {
      nickname: ''
    },
    headBase64: '',
    theme: wx.getSystemInfoSync().theme,
    options: {},
    rules: [{
      name: 'nickname',
      rules: {
        required: true,
        message: '昵称必填'
      },
    }]
  },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.checkIsRegister()
    let _this = this;
    _this.setData({
      options
    });
  },
  onChange(e) {
    let field = e.target.dataset.field
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },
  submitForm() {
    this.selectComponent('#form').validate((valid, errors) => {
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {
        if (!this.data.headBase64) {
          this.setData({
            error: '请点击头像上传或选择微信头像！'
          })

        } else {
          // 已通过 去注册登陆
          let e = {
            headimage: this.data.headBase64,
            nickname: this.data.formData.nickname
          }
          this.getUserInfo(e)
        }

      }
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.setData({
      avatarUrl,
    })
    let _this = this
    wx.getFileSystemManager().readFile({
      filePath:avatarUrl,
      encoding:'base64',
      success:res=>{
        console.log('res',res);
        _this.setData({
          headBase64:`data:image/png;base64,${res.data}`
        })
      }
    })
    // wx.uploadFile({
    //   filePath: avatarUrl,
    //   name: 'file',
    //   url: baseUrl['baseUrl'] + '/api/Files',//服务器端接收图片的路径
    //   header: {'Authorization': wx.getStorageSync('token')},
    //   formData: {
    //     'name': 'test111111.png',
    //     'sBusinessType':'type'
    //  },
    //   success:function(res){
    //     console.log(res);//发送成功回调
    //   },
    //   fail:function(res){
    //     console.log(res);//发送失败回调，可以在这里了解失败原因
    //   }
    // })
  },
  checkIsRegister() {
    let _this = this
    wx.login({
      success(res) {
        WXAPI.checkRegister({
          sAppid:config.appId,
          sCode: res.code
        }).then(res => {
          console.log(res);
          if(res.data.data) {
            wx.showLoading({
              title: "检测到已注册\n正在自动登录",
              mask: true
            });
            _this.setData({
              isRegister: true
            })
            _this.getUserInfo()
          }
        })
      }
    })

    
  },
  /**
   * 授权登录
   */
  getUserInfo(e) {
    let _this = this;
    App.getUserInfo(e, () => {
      // 跳转回原页面
      // _this.onNavigateBack(1);
      wx.switchTab({
        url: '/pages/index/index',
      })
    });
  },

  /**
   * 暂不登录
   */
  onNotLogin() {
    let _this = this;
    // 跳转回原页面
    _this.onNavigateBack(_this.data.options.delta);
  },

  /**
   * 授权成功 跳转回原页面
   */
  onNavigateBack(delta) {
    wx.navigateBack({
      delta: Number(delta || 1)
    });
  },

})